package com.mashibing.helloworld;

import com.mashibing.util.RabbitMQConnectionUtil;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.DeliverCallback;
import org.junit.Test;

/**
 * Hello World方式的Consumer
 * @author zjw
 */
public class Recv {

    private final static String QUEUE_NAME = "hello";

    @Test
    public void consume() throws Exception {
        //1. 获取链接对象
        Connection connection = RabbitMQConnectionUtil.getConnection();

        //2. 构建通道
        Channel channel = connection.openChannel().get();

        //3. 交换机提供了，队列需要手动创建
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);

        //4. 消费回调函数
        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            System.out.println(" [x] Received '" + message + "'");
        };

        //5. 监听队列
        channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> { });
        System.out.println(" [x] Received '开始监听" + QUEUE_NAME + "'");

        //6. 避免程序停止
        System.in.read();
    }
}
